package de.lulusoft.anothertorrent.core.xmlrpc;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;


public class XmlrpcManager {
	
//	private static XmlrpcManager instance = null;
	
	private XmlRpcClientConfigImpl config = null;
	private XmlRpcClient client = null;
	private String m_url = null;
	private boolean m_connected = false;

	public XmlrpcManager()
	{	

	}
	
	public boolean isConnected() {
		return m_connected;
	}

	public void connect(String url)
	{
		m_url = url;
		config = new XmlRpcClientConfigImpl();
		config.setEnabledForExtensions(true);
	    try {
			config.setServerURL(new URL(m_url));
			m_connected = true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	    client = new XmlRpcClient();
	    client.setConfig(config);
	    client.setTypeFactory(new RTorrentTypeFactory(client));
	}
	
	public Object sendSimpleCommand(String cmd)
	{
		if (!m_connected)
			return null;
		Object[] params = new Object[]{};
		Object result = null;
		try {
			result = client.execute(cmd, params);
		} catch (XmlRpcException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public Object sendCommand(String cmd, Object[] params)
	{
		if (!m_connected)
			return null;
		Object result = null;
		
		try {
			
			result = client.execute(cmd, params);
		} catch (XmlRpcException e) {
			result = e.getMessage();
			e.printStackTrace();
		}
		return result;
	}
}
